/*
 * Copyright (c) 2020-2021. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.depsea.log.helper;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tgchina.swift.common.aware.ApplicationNameAware;
import lombok.extern.slf4j.Slf4j;
import org.depsea.log.config.properties.LogPointAspectProperties;
import org.depsea.log.model.ExceptionInfo;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.scheduling.annotation.Async;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 将异常信息记录到ES中
 *
 * @author Wang Chengwei
 * @since 1.0.0 2021/11/3 9:53
 */
@Slf4j
public class ExceptionElasticsearchLogHelper implements ApplicationNameAware {

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    private final LogPointAspectProperties logPointAspectProperties;

    private String applicationName;

    /**
     * JSON序列化
     */
    private final ObjectMapper objectMapper = new ObjectMapper();

    public ExceptionElasticsearchLogHelper(ElasticsearchRestTemplate elasticsearchRestTemplate, LogPointAspectProperties logPointAspectProperties) {
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
        this.logPointAspectProperties = logPointAspectProperties;
    }

    @Override
    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    @Async
    public void resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ExceptionInfo exceptionInfo = ExceptionInfo.create(this.applicationName, handler, ex);
        exceptionInfo.setRequestUrl(request.getRequestURI());
        exceptionInfo.setRequestMethod(request.getMethod());

        try {
            exceptionInfo.setRequestParameterMap(objectMapper.writeValueAsString(request.getParameterMap()));
        } catch (JsonProcessingException e) {
            log.warn("参数序列化失败");
        }
        String indexName = this.logPointAspectProperties.getExceptionLogIndexNamePrefix() + "-"
                + LocalDate.now().format(DateTimeFormatter.ofPattern(this.logPointAspectProperties.getDatePattern()));
        IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);
        this.elasticsearchRestTemplate.save(exceptionInfo, indexCoordinates);
    }
}
